<?php
/**
 * Created by PhpStorm.
 * User: dev
 * Date: 24/9/14
 * Time: 11:15 AM
 */

class Banner_Admin_Create_Controller extends Admin_Controller{

    public $restful = true;

    public function __construct()
    {
        parent::__construct();
        //--Your Code --//
        $this->theme->set_theme("admin") ;
    }

    public function get_index(){
        $this->theme->title("Admin: New Banner");
        $data['title'] = 'Add New Banner';
        return $this->theme->render('banner::admin.create',$data);
    }

    public function post_index(){

    	$rules = array(
    	
    			'title' => 'required',
    			'from_date' => 'required',
    			'to_date' => 'required',
    	);
    	
    	
    	
    	
    	$validator = Validator::make(Input::get(), $rules);
    	
    	if( $validator->fails() )
    	{
    		return Redirect::back()->with_input()->with_errors($validator)->with('message','<div class="alert alert-warning">Invalid Operation !</div>');
    	}
    	else
    	{
    		 
        $filename = Input::file('image.name');
        $extension = File::extension($filename);
        $image = Input::file('image');
        $dirPath = path('storage').'uploads/banners/';
        $filename = $image['name'];

        if($filename == FALSE){
        	return Redirect::back()->with('message','<div class="alert alert-warning">Browse filed can not be null..</div>');
        }
        
        $createFolders = true;
        $backgroundColor = null;
        $imageQuality = 100;

        //--NEW NAME --//
        $filename = md5($filename).'.'.$extension;

        $layer = PHPImageWorkshop\ImageWorkshop::initFromPath($image['tmp_name']);

        $thumbWidth = 300; // px
        $thumbHeight = 250;
        $conserveProportion = false;
        $positionX = 0; // px
        $positionY = 0; // px
        $position = 'LT';

        $layer->resizeInPixel($thumbWidth, $thumbHeight, $conserveProportion, $positionX, $positionY, $position);
        $layer->save($dirPath, $filename, $createFolders, $backgroundColor, $imageQuality);

        $post_data = array(
            'file' => $filename,
            'title' => trim(Input::get('title')),
            'link' => trim(Input::get('link')),
            'from_date' => date_format(date_create(Input::get('from_date')),"Y-m-d"),
            'to_date' => date_format(date_create(Input::get('to_date')),"Y-m-d"),
            'max_impressions' => (int)Input::get('max_impressions'),
            'max_clicks' => (int)Input::get('max_clicks'),
            'clicks' => 0,
            'impressions' => 0,
        	'page' => (int) Input::get('page'),	
            'created_at' => Commoncall::current_timestamp(),
            'modified_at' => Commoncall::current_timestamp(),
        );

        DB::table('banners')->insert($post_data);
        return Redirect::back()->with('message','<div class="alert alert-info">Data Successfully added !</div>');
    	}
    }

} 